import numpy as np
import acl

try:
    # 初始化 AscendCL
    acl.init()

    # 加载算子库
    lib_path = "add_custom.so"
    acl.op.load(lib_path)

    # 准备输入数据
    input_shape = (10, 10)
    input_data_x = np.random.randn(*input_shape).astype(np.float16)
    input_data_y = np.random.randn(*input_shape).astype(np.float16)

    # 创建输入和输出 Tensor
    input_tensor_x = acl.tensor.create(input_data_x)
    input_tensor_y = acl.tensor.create(input_data_y)
    output_tensor = acl.tensor.create(shape=input_shape, dtype=np.float16)

    # 配置算子参数
    op_name = "AddCustom"
    op_params = {
        "x": input_tensor_x,
        "y": input_tensor_y,
        "z": output_tensor
    }

    # 执行算子
    acl.op.execute(op_name, op_params)

    # 获取输出数据
    output_data = acl.tensor.to_numpy(output_tensor)

    # 验证结果
    expected_output = input_data_x + input_data_y
    error = np.max(np.abs(output_data - expected_output))
    if error < 1e-3:
        print("算子验证通过！")
    else:
        print("算子验证失败，误差：", error)

except Exception as e:
    print(f"测试过程中出现错误：{e}")
finally:
    # 释放资源
    if 'input_tensor_x' in locals():
        acl.tensor.destroy(input_tensor_x)
    if 'input_tensor_y' in locals():
        acl.tensor.destroy(input_tensor_y)
    if 'output_tensor' in locals():
        acl.tensor.destroy(output_tensor)
    if 'lib_path' in locals():
        acl.op.unload(lib_path)
    acl.finalize()